<?php

if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
 	require_once (APPLICATION_PATH . "\\models\\connectionDb.php");
} else {
    require_once (APPLICATION_PATH . "//models//connectionDb.php");
}


class Application_Model_DbTable_Threads extends Zend_Db_Table_Abstract
{

    protected $_name = 'Threads';
    protected $_primary = 'id';

	public function createThread($title, $text, $userID)
 	{
 		$time = new Zend_Date();
    	$time1=$time->toString('YYYY-MM-dd HH:mm:ss');
  		
    	$data = array(
	   		'Title' => $title,
	   		'Text' => $text,
	   		'DateCreated' => $time1,
    		'User_id' => $userID,
  		);
  		return $this->insert($data);		
 	}
 	
	public function getThread($id)
    {
     	$id = (int)$id;
  		$row = $this->fetchRow('id = ' . $id);         
  		if (empty($row)) {
   			return null;
  		}
  		return $row->toArray();
    }
    
    public function editThread($id, $title, $text)
    {
    	$data = array(
    		'Title' => $title,
			'Text' => $text,			
		);
		$this->update($data,  'id = '. (int)$id);
    }
    
    public function getUserThreads($userID)
    {
    	$userID = (int)$userID;
    	$rows = $this->fetchAll("User_id = '" . $userID ."'");
    	return $rows;
    }
    
    public function deleteThread($id)
    {
    	try{
			$this->delete('id =' . (int)$id);
		}
		catch (Zend_Exception $e) {  
			echo "Error message: " . $e->getMessage() . "\n";
        }
    }
    
	public function getSearchThreads($thread_name,$tags)
    {
    	try{
    		
    		$sql ="select distinct Threads.*, Users.username";
			$sql .=" from Threads";
			$sql .=" left join SearchTerm on SearchTerm.Thread_id = Threads.id";
			$sql .=" left join Tag on Tag.id = SearchTerm.Tag_id";
			$sql .=" inner join Users on Users.id = Threads.User_id";
			$sql .=" where 1=1";
			$sql .=" and Threads.Title Like '%". $thread_name ."%'";
			$sql .=" ".$tags;
    		
    		$db = connectionDb::connectDB();		
			$rows = $db->fetchAll($sql);			
	  					 
	    	if (!$rows) {
	   			return null;
	  		}
	  		return $rows;
    	
    	}
    	catch (Zend_Exception $e) {  
			echo "Error message: " . $e->getMessage() . "\n";
        }
    }

}

